package com.feihong.txgw.ui.activity.kaika;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.blankj.utilcode.util.LogUtils;
import com.feihong.txgw.R;
import com.feihong.txgw.http.HttpTools;
import com.feihong.txgw.http.RefreshToken;
import com.feihong.txgw.inter.contract.kaika.IKaikaSubmitContract;
import com.feihong.txgw.json.kaika.KaiKaSubmitOrder;
import com.feihong.txgw.message.LoginMessage;
import com.feihong.txgw.message.RefreshOrder;
import com.feihong.txgw.tx_precenter.KaikaSubmitMainPrecenter;
import com.feihong.txgw.ui.activity.order.MyOrderActivity;
import com.feihong.txgw.ui.activity.order.PayActivity;
import com.feihong.txgw.ui.activity.order.PaySuccessActivity;
import com.feihong.txgw.ui.mvp.BaseMVPCompateActivity;
import com.feihong.txgw.ui.mvp.precenter.AbBasePrecenter;
import com.feihong.txgw.utils.TImageUtils;
import com.feihong.txgw.utils.facetools.UploadAndVerifyFace;
import com.feihong.txgw.utils.facetools.UploadCallBack;
import com.feihong.txgw.utils.manage.ThreadPoolManager;
import com.feihong.txgw.utils.sign.SignToken;
import com.feihong.txgw.view.WebView4Scroll;
import com.just.agentweb.AgentWeb;
import com.megvii.licensemanager.Manager;
import com.megvii.livenessdetection.LivenessLicenseManager;
import com.megvii.livenesslib.LivenessActivity;
import com.megvii.livenesslib.OpenActiviyuCallBackListener;
import com.megvii.livenesslib.util.ConUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;
import top.zibin.luban.Luban;

import static android.view.View.OVER_SCROLL_NEVER;

/**
 * Created by Sabirjan on 2017/7/4.
 * TXGWApp.
 * 飞宏电子
 * 开卡步骤4 提交订单页面
 */
@RuntimePermissions
public class KaiKaStep4Activity extends BaseMVPCompateActivity<IKaikaSubmitContract.AbKaikaSubmitMainPrecenter> implements IKaikaSubmitContract.IKaikaSubmitMainView {
    private String phoneNum = "";
    private String phoneNumID = "";
    private String iccid = "";
    private String taocanJson = "";
    private AgentWeb mAgentWeb;
    @BindView(R.id.rel_contantframe)
    RelativeLayout webviewFrame;
    /**
     * 身份证数据
     */
    private String idcard = "";
    /**
     * 身份证照片
     */
    private String photo = "";
    /**
     * 身份证姓名
     */
    private String idName = "";

    /**
     * 拍摄的身份证真反面id标识   (待处理优化)
     */
    private String mIDCardImgFrontID, mIDCardImgBackID;

    @BindView(R.id.connect_net_error_layout)
    LinearLayout mConnectErrorLayout;
    @BindView(R.id.re_query_data_layout)
    LinearLayout mRequeryDataBtn;
    /**
     * 活体检测中获取到的照片
     */
    private String img1 = "";
    /**
     * 人脸对比结果 默认0
     */
    private String faceResult = "0";
    private String yuyueOrderSn;
    private int mFromBooking;
    /**
     * 拍摄身份证图片的requestCode
     */
    private static final int CAMERA_IDCARD_REQUEST_CODE = 11;

    /**
     * 刷新token的what值
     */
    private static final int REFRESH_TOKEN_WHAT = 10;
    /**
     * 活体检测联网检测成功与失败的what值
     */
    private static final int HTJC_NETWORK_SUCCESS_WHAT = 1;
    private static final int HTJC_NETWORK_ERROR_WHAT = 2;
    /**
     * 身份证图片压缩成功与否 what值
     */
    private static final int IDCARD_COMPRESS_ERROR_WHAT = 4;
    private AgentWeb.PreAgentWeb mPreAgentWeb;

    /**
     * 活体检测信息
     */
    private String htjcJson = "";

    /**
     * 身份证正面 背面 base64
     */

    /**
     * 活体检测   身份证正面拍照 身份证背面拍照  权限类型
     */
    private final static String FACE_CHACK = "FACE_CHACK";
    private final static String IDCARD_CAMERA_PERMISSION = "IDCARD_CAMERA_PERMISSION";
    private String mPermissionType;

    /**
     * 拍摄身份证图片的 uri以及 图片的本地保存路径
     */
    private Uri mContentUri;
    private File picFile;

    /**
     * 刷新token
     */
    private void refreshToken() {
        ThreadPoolManager.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                RefreshToken.getInstance().RetrofitRefreshTokenForGet();
                Message message = Message.obtain();
                message.what = REFRESH_TOKEN_WHAT;
                mHandler_Init.sendMessage(message);
            }
        });
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("mFromBooking", mFromBooking);
        outState.putString("iccid", iccid);
        outState.putString("phoneNum", phoneNum);
        outState.putString("taocanJson", taocanJson);
        outState.putString("yuyueOrderSn", yuyueOrderSn);
    }

    @Override
    public void setTheme() {

    }

    @Override
    public int setLayoutID() {
        return R.layout.activity_kaika_step3;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        KaikaManager.getmKaikaManager().addStack(this);
//        if (savedInstanceState != null) {
//            mFromBooking = savedInstanceState.getInt("mFromBooking",0);
//            iccid = savedInstanceState.getString("iccid");
//            phoneNum = savedInstanceState.getString("phoneNum");
//            taocanJson = savedInstanceState.getString("taocanJson");
//            yuyueOrderSn = savedInstanceState.getString("yuyueOrderSn");
//        } else {
            mFromBooking = getIntent().getIntExtra(KaiKaActivity.INTENT_FROM_BOOKING, 0);
            iccid = getIntent().getStringExtra(KaiKaActivity.INTENT_ICCID);
//        iccid = "2017081361111111111";
            phoneNum = getIntent().getStringExtra(KaiKaActivity.INTENT_PHOE_NUM);
            taocanJson = getIntent().getStringExtra("json");
            yuyueOrderSn = getIntent().getStringExtra(KaiKaActivity.INTENT_ORDERSN);
//
//        }
        if (TextUtils.isEmpty(yuyueOrderSn)) {
            if (TextUtils.isEmpty(iccid) || TextUtils.isEmpty(phoneNum) || TextUtils.isEmpty(taocanJson)) {
                showSystemToast("页面信息有误！");
                finish();
            }
        }
        setPageTitle("号卡详情");
        setBackButtonFinish();
        mRequeryDataBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mConnectErrorLayout.setVisibility(View.GONE);
                refreshToken();
            }
        });
        WebView webView = new WebView(getActivity());
        webView.setVerticalScrollBarEnabled(false);
        webView.setOverScrollMode(OVER_SCROLL_NEVER);
        mPreAgentWeb = AgentWeb.with(this)
                .setAgentWebParent(webviewFrame, new RelativeLayout.LayoutParams(-1, -1))
                .useDefaultIndicator()
                .setWebChromeClient(mWebChromeClient).setWebView(webView)
                .setWebViewClient(mWebViewClient)
                .setMainFrameErrorView(R.layout.agentweb_errorlayout, R.id.agentweb_re_query_data_layout)
                .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
                .createAgentWeb()
                .ready();
    }

    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return true;
            // return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return true;
            // return super.shouldOverrideUrlLoading(view, request);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            //super.onReceivedSslError(view, handler, error);
            handler.proceed();
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
        }
    };

    private WebChromeClient mWebChromeClient = new WebChromeClient() {


    };

    @Override
    public void bindData() {
        refreshToken();
    }

    private void loadPage() {
        String url = HttpTools.KAIKA_STEP4_WEBURL + "?";
        try {
            HashMap<String, String> params = new HashMap<>();
            if (!TextUtils.isEmpty(yuyueOrderSn)) {
                params.put("order_sn", yuyueOrderSn);
                params.put("fromBooking", String.valueOf(mFromBooking));
                String param = new SignToken().setSigen(params);
                url = url + param;
            } else {
                params.put("iccid", iccid);
                params.put("phonenum", phoneNum);
                JSONObject object = new JSONObject(taocanJson);
                JSONObject jsonparams = object.getJSONObject("params");
                Iterator<String> maps = jsonparams.keys();
                while (maps.hasNext()) {
                    String key = maps.next();
                    String val = jsonparams.getString(key);
                    //url = url + "&" + key + "=" + val;
                    params.put(key, val);
                }
                String getParams = new SignToken().setSigen(params);
                url = url + getParams;
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        mAgentWeb = mPreAgentWeb.go(url);
        //屏蔽长按弹出复制按钮
        mAgentWeb.getWebCreator().getWebView().setOnLongClickListener(new View.OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });

        mAgentWeb.getJsInterfaceHolder().addJavaObject("android", new Step4Interface(mAgentWeb, this, iccid, phoneNum, taocanJson, actionCallBack));
        //水平不显示
        mAgentWeb.getWebCreator().getWebView().setHorizontalScrollBarEnabled(false);
        //垂直不显示
        mAgentWeb.getWebCreator().getWebView().setVerticalScrollBarEnabled(false);
        if (mAgentWeb != null) {
            mAgentWeb.getWebLifeCycle().onResume();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mAgentWeb != null) {
            mAgentWeb.getWebLifeCycle().onResume();
        }
    }

    @Override
    protected void onPause() {
        if (mAgentWeb != null) {
            mAgentWeb.getWebLifeCycle().onPause();
        }
        super.onPause();
    }

    /**
     * 补传信息所需的活体检测图片
     */
    private Bitmap mBitmap;

    /**
     * 进行活体检测
     */
    private void start_htjc() {
        try {
            JSONObject obj = new JSONObject(htjcJson);
            idcard = obj.getString("idcard");
            photo = obj.getString("photo");
            idName = obj.getString("realname");

            mIDCardImgBackID = obj.optString("img_back_id");
            mIDCardImgFrontID = obj.optString("img_front_id");
            if (idcard == null || idcard.trim().length() < 15) {
                showDialog("错误", "身份证号码有误！");
                return;
            }
            if (idName == null || idName.trim().length() == 0) {
                showDialog("错误", "身份证姓名有误！");
                return;
            }
            if (photo == null || photo.trim().length() < 0) {
                showDialog("错误", "照片数据有误！");
                return;
            }


        } catch (Exception ex) {
            ex.printStackTrace();
            showDialog("错误", "数据格式有误，无法解析！");
            return;
        }

        //进行活体检测
        showProgressDialog("正在授权...");
        netWorkWarranty();//第一步授权
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            chackActivityState();
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    private String uuid = "";

    /**
     * 联网授权
     */
    private void netWorkWarranty() {
        uuid = ConUtil.getUUIDString(this);
        ThreadPoolManager.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                Manager manager = new Manager(getActivity());
                LivenessLicenseManager licenseManager = new LivenessLicenseManager(getActivity());
                manager.registerLicenseManager(licenseManager);

                manager.takeLicenseFromNetwork(uuid);
                if (licenseManager.checkCachedLicense() > 0) {
                    mHandler_Init.sendEmptyMessageDelayed(HTJC_NETWORK_SUCCESS_WHAT, 500);
                } else {
                    mHandler_Init.sendEmptyMessageDelayed(HTJC_NETWORK_ERROR_WHAT, 500);
                }
            }
        });

    }

    Handler mHandler_Init = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (activityIsDestory()) {
                return;
            }
            switch (msg.what) {
                case HTJC_NETWORK_SUCCESS_WHAT:
                    dismissProgressDialog();
                    //成功
                    Intent intent = new Intent(getActivity(), LivenessActivity.class);
                    LivenessActivity.setCallBackListener(mCallBack);
                    startActivity(intent);
                    break;
                case HTJC_NETWORK_ERROR_WHAT:
                    dismissProgressDialog();
                    //联网授权失败！请检查网络或找服务商
                    showDialog("授权失败", "联网授权失败！请检查网络或找服务商！");
                    break;
                case REFRESH_TOKEN_WHAT:
                    dismissProgressDialog();
                    loadPage();
                    break;
                case IDCARD_COMPRESS_ERROR_WHAT:
                    dismissProgressDialog();
                    showDialog("", "图片处理失败，请重新拍照");
                    break;
                default:
                    break;
            }
        }
    };

    OpenActiviyuCallBackListener mCallBack = new OpenActiviyuCallBackListener() {
        @Override
        public void callBack(final Bitmap bmp, String delta, Map<String, byte[]> images) {


            showProgressDialog("正在验证...");
            UploadAndVerifyFace uploadAndVerifyFace = new UploadAndVerifyFace(getActivity(), new UploadCallBack() {
                //身份证照片上传结果和活体检测拿出来的照片和身份证照片对比
                //上传成功，但是对比
                @Override
                public void success(String uploadImageUrl, int result, String faceMessage) {

                    dismissProgressDialog();
                    if (1 == result) {
                        LogUtils.i(TAG + ":  success() called with: uploadImageUrl = [" + uploadImageUrl + "], faceresult = [" + result + "]" + "   " + faceMessage);
                        img1 = uploadImageUrl;
                        faceResult = result + "";
                        mBitmap = bmp;
                        showDialog("", "人脸比对成功,可以提交订单了");
                        dismissProgressDialog();
                        mAgentWeb.getJsAccessEntrace().quickCallJs("detect('" + uploadImageUrl + "'," + result + ",'" + faceMessage + "')");
//                        }
                    } else {
                        dismissProgressDialog();
                        showDialog(null, "图片比对失败！请重新进行活体检测！");
                    }
                }

                @Override
                public void error(String error) {
                    dismissProgressDialog();
                    showDialog("上传失败", "图片上传失败！请重试");
                    LogUtils.e(TAG + ": error() called with: error = [" + error + "]");
                }
            });

            uploadAndVerifyFace.initData(bmp, photo, idcard, delta, images);
            uploadAndVerifyFace.startUpload();//开始上传并身份证照片对比

        }

        @Override
        public void error(String message) {
            showSystemToast("活体检测失败！原因:" + message);
        }

        @Override
        public void finish() {
        }
    };

    @NeedsPermission(Manifest.permission.CAMERA)
    void showCamera() {
        switch (mPermissionType) {
            case FACE_CHACK:
                // 活体检测
                start_htjc();
                break;
            case IDCARD_CAMERA_PERMISSION:
                goCameraIDCard(IDCARD_CAMERA_PERMISSION);
                break;
            default:
                break;
        }
    }


    @Override
    public void submitNormalOrderResult(KaiKaSubmitOrder result) {
        dismissProgressDialog();
        if (result.getCode() == 200) {
            //跳到付款页面
            Intent intent = new Intent();
            intent.setClass(KaiKaStep4Activity.this, PayActivity.class);
            intent.putExtra(PayActivity.INTENT_ORDER_ID, result.getData().getOrder_sn());
            intent.putExtra(PayActivity.INTENT_PAY_TYPE, PayActivity.PAY_TYPE_KAIKA);
            intent.putExtra(PayActivity.INTENT_PRICE, result.getData().getPrice() + "");
            intent.putExtra(PayActivity.INTENT_TITLE, result.getData().getBody());
            startActivity(intent);
            KaikaManager.getmKaikaManager().clearAll();

        } else if (result.getCode() == 300) {
            //跳到成功页面

            Intent intent = new Intent();
            intent.setClass(KaiKaStep4Activity.this, PaySuccessActivity.class);
            intent.putExtra(PaySuccessActivity.INTENT_TYPE, PaySuccessActivity.TYPE_SUBMIT_SUCCESS);
            startActivity(intent);
            KaikaManager.getmKaikaManager().clearAll();

        } else {
            showDialog("错误", "提交失败：\n" + result.getMsg());
        }
    }

    @Override
    public void submitNormalOrderError() {
        dismissProgressDialog();
    }

    @Override
    public void submitYuyueOrderResult(String result) {
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(result);
            if ("200".equals(jsonObject.optString("code"))) {
                Intent intent;
                JSONObject orderInfoJsonObject = jsonObject.optJSONObject("data");
                if ("1".equals(orderInfoJsonObject.optString("fromBooking"))) {
                    intent = new Intent(KaiKaStep4Activity.this, MyOrderActivity.class);
                    EventBus.getDefault().post(new RefreshOrder());
                } else {
                    intent = new Intent(KaiKaStep4Activity.this, PayActivity.class);
                    intent.putExtra(PayActivity.INTENT_ORDER_ID, orderInfoJsonObject.optString("order_sn"));
                    intent.putExtra(PayActivity.INTENT_PAY_TYPE, PayActivity.PAY_TYPE_KAIKA);
                    intent.putExtra(PayActivity.INTENT_PRICE, orderInfoJsonObject.optString("price"));
                    intent.putExtra(PayActivity.INTENT_TITLE, orderInfoJsonObject.optString("body"));
                }
                startActivity(intent);
                KaikaManager.getmKaikaManager().clearAll();
            } else if ("300".equals(jsonObject.optString("code"))) {
                Intent intent = new Intent();
                intent.setClass(KaiKaStep4Activity.this, PaySuccessActivity.class);
                intent.putExtra(PaySuccessActivity.INTENT_TYPE, PaySuccessActivity.TYPE_SUBMIT_SUCCESS);
                startActivity(intent);
                KaikaManager.getmKaikaManager().clearAll();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }


    @Override
    public void submitYuyueOrderError() {
        dismissProgressDialog();
        showSystemToast(getString(R.string.connect_service_error));
    }

    @Override
    public void kaikaAuthIDCardResult(String result) {
        dismissProgressDialog();
        mAgentWeb.getJsAccessEntrace().quickCallJs("getIdcard", result);
    }

    @Override
    public void kaikaAuthIDCardError() {
        dismissProgressDialog();
        mAgentWeb.getJsAccessEntrace().quickCallJs("getIdcard", "");
    }

    @Override
    public void kaikaUploadIDCardImgResult(String result) {
        dismissProgressDialog();
        mAgentWeb.getJsAccessEntrace().quickCallJs("shoot_info('" + result + "')");
    }


    @Override
    public void loadDataComplated() {

    }

    @Override
    public void loadDataError() {

    }

    @NonNull
    @Override
    public AbBasePrecenter initPresenter() {
        return KaikaSubmitMainPrecenter.create();
    }

    public interface ActionCallBack {
        public void huotijiance(String cardInfo);

        public void tijiaoDingDan();

        public void getParams(String json);

        void yuyueOrder(String json);

        /**
         * 调起相机身份证拍照
         */
        void idCardCamera();
    }

    private ActionCallBack actionCallBack = new ActionCallBack() {
        @Override
        public void huotijiance(String cardInfo) {
            LogUtils.i(TAG + ":活体检测第一步，服务端回传信息：" + cardInfo);
            htjcJson = cardInfo;
            mPermissionType = FACE_CHACK;
            KaiKaStep4ActivityPermissionsDispatcher.showCameraWithCheck(KaiKaStep4Activity.this);
        }

        @Override
        public void tijiaoDingDan() {
            //进行提交订单
            if (TextUtils.isEmpty(iccid) || TextUtils.isEmpty(taocanJson) || TextUtils.isEmpty(phoneNum) || TextUtils.isEmpty(idcard) || TextUtils.isEmpty(idName)) {
                showSystemToast("参数不正确！关闭页面，重新进入！");
                return;
            }
            showProgressDialog("正在提交订单...");
            HashMap<String, String> params = new HashMap<>(16);
            params.put("iccid", iccid);
            try {
                JSONObject object = new JSONObject(taocanJson);
                JSONObject jsonparams = object.getJSONObject("params");
                Iterator<String> maps = jsonparams.keys();
                while (maps.hasNext()) {
                    String key = maps.next();
                    String val = jsonparams.getString(key);
                    //url = url + "&" + key + "=" + val;
                    params.put(key, val);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            params.put("real_name", idName);
            params.put("idcard", idcard);
            params.put("phonenum", phoneNum);
            params.put("rldb_pass", faceResult);
            params.put("img1", img1);
            params.put("img2", photo);
            params.put("img_front_id", mIDCardImgFrontID);
            params.put("img_back_id", mIDCardImgBackID);
            mPresenter.submitNormalOrder(params);
        }

        @Override
        public void getParams(String json) {
            mPresenter.kaikaAuthResult(json);
        }

        @Override
        public void yuyueOrder(String json) {
            HashMap<String,String> mParams = new HashMap<>();
            LogUtils.i(TAG + ": 预支付订单信息-->" + json);
            mParams.put("idcard",idcard);
            mParams.put("order_sn",yuyueOrderSn);
            mParams.put("rldb_pass","1");
            mParams.put("img1",TImageUtils.bitmap2String(mBitmap));
            mParams.put("real_name",idName);
            mParams.put("img2",photo);
            mParams.put("img_front_id",mIDCardImgFrontID);
            mParams.put("img_back_id",mIDCardImgBackID);
            mParams.put("iccid",iccid);
            mParams.put("fromBooking",String.valueOf(mFromBooking));
            mPresenter.submitYuyueOrder(mParams);
        }

        @Override
        public void idCardCamera() {
            mPermissionType = IDCARD_CAMERA_PERMISSION;
            KaiKaStep4ActivityPermissionsDispatcher.showCameraWithCheck(KaiKaStep4Activity.this);
        }

    };

    @OnShowRationale(Manifest.permission.CAMERA)
    void rationaleForCamera(final PermissionRequest request) {
        request.proceed();
    }

    @OnPermissionDenied(Manifest.permission.CAMERA)
    void onKaiKaCameraDenied() {
        // NOTE: Deal with a denied permission, e.g. by showing specific UI
        // or disabling certain functionality
    }

    /**
     * 图片名称  正面 侧面
     *
     * @param imgName
     */
    private void goCameraIDCard(String imgName) {
        String cachePath = getApplicationContext().getExternalCacheDir().getPath();
        picFile = new File(cachePath, imgName + ".jpg");
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            mContentUri = FileProvider.getUriForFile(this, "com.feihong.txgw.updatefileprovider", picFile);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mContentUri);
        } else {
            mContentUri = Uri.fromFile(picFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mContentUri);
        }
        startActivityForResult(intent, CAMERA_IDCARD_REQUEST_CODE);
        getActivity().overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // NOTE: delegate the permission handling to generated method
        KaiKaStep4ActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CAMERA_IDCARD_REQUEST_CODE:
                if (resultCode != RESULT_OK) {
                    return;
                }
                showProgressDialog("图片处理中");
                ThreadPoolManager.getInstance().execute(new Runnable() {
                    @Override
                    public void run() {
                        FileOutputStream out = null;
                        try {
                            Bitmap newBitmap = BitmapFactory.decodeFile(picFile.getAbsolutePath());
                            if (newBitmap.getHeight() < newBitmap.getWidth()) {
                                newBitmap = TImageUtils.exifBitmap(newBitmap, 90);
                            }
                            File file = new File(getApplicationContext().getExternalCacheDir().getPath(), "kaikaIDCard.jpg");
                            out = new FileOutputStream(file);
                            newBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
                            List<File> files = Luban.with(KaiKaStep4Activity.this).load(file).ignoreBy(500).get();
                            RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), files.get(0));
                            MultipartBody.Part imageBodyPart = MultipartBody.Part.createFormData("idcard_img_file", file.getName(),imageBody );
                            mPresenter.kaikaUploadIDCardImg(imageBodyPart);
//                            Callback.Cancelable upIDCardRequestCallBack = App.getApp().getHttpTools().kaikaQueryIDCardInfo(files.get(0), upLoadIDCardImgCallBack);
//                            mActivityRequestList.add(upIDCardRequestCallBack);
                        } catch (IOException e) {
                            e.printStackTrace();
                        } finally {
                            if (out != null) {
                                try {
                                    out.flush();
                                    out.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                });
                break;
            default:
                break;
        }
    }

    @Override
    public void onDestroy() {
        try {
            webviewFrame.removeAllViews();
            if (mAgentWeb != null) {
                mAgentWeb.clearWebCache();
                mAgentWeb.destroy();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        if (mHandler_Init != null && mHandler_Init.getLooper() == Looper.getMainLooper()) {
            mHandler_Init.removeCallbacksAndMessages(null);
        }
        super.onDestroy();
    }
}
